package gowcage.testandroid;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.gowcage.testandroid.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static gowcage.testandroid.DownLoadUtil.WPS_DownLoad_Url;

/**
 * Created by Administrator on 2017/4/11.
 */

public class OpenDocActivity extends Activity {

    /** 支持方式
     *
     * 模式               说明
     * ReadOnly     只读模式
     * Normal        正常模式
     * ReadMode   打开直接进入阅读器模式
     * SaveOnly     保存模式（打开文件、另存、关闭）
     */

    /** 打开文件
     *
     * 参数名                  参数说明                                             类型              默认值
     *
     * OpenMode            打开文件的模式                                  String           "Normal"
     * SendSaveBroad     文件保存时是否发送广播                     boolean         false
     * SendCloseBroad    文件关闭时是否发送广播                     boolean         false
     * ThirdPackage        第三方包名，关闭的广播会包含该项    String
     * ClearBuffer            关闭文件时是否清空临时文件              boolean         false
     * ClearTrace            关闭文件时是否删除使用记录               boolean         false
     * ClearFile               关闭文件时是否删除打开的文件            boolean         false
     * ViewProgress        文件上次查看的进度                             float              0.0%
     * AutoJump             是否自动跳转到上次查看的进度            boolean        false
     * SavePath              文件保存的路径                                    String
     * ViewScale             文件上次查看的视图的缩放                   float              1.0
     * ViewScrollX          文件上次查看的视图的X坐标                  int                 0
     * ViewScrollY          文件上次查看的视图的Y坐标                  int                  0
     */

    /** 保存文件
     *
     * （文件保存时会发送一个"cn.wps.moffice.file.save"的广播，
     * 第三方程序根据需要接听广播。
     * 广播含有文件的路径信息，打开文件时传递的包名等，
     * 使用时酌情解析）
     *
     * 参数名                  参数说明                    类型
     *
     * OpenFile            文件最初的路径            String
     * ThirdPackage     传入的第三方包名        String
     * SavePath           文件这次保存的路径     String
     */

    /**
     * 关闭文件
     * <p>
     * （文件关闭时会发送一个"cn.wps.moffice.file.close"的广播，
     * 第三方程序根据需要接听广播。
     * 广播含有文件的路径信息，打开文件时传递的包名等，
     * 使用时酌情解析）
     * <p>
     * 参数名                  参数说明                            类型              默认值
     * <p>
     * CloseFile            关闭文件的路径                     String
     * ThirdPackage     传入的第三方包名                 String
     * ViewProgress     文件查看的进度                      float               0.0%
     * ViewScale          文件上次查看的视图的缩放      float               1.0
     * ViewScrollX        文件上次查看的视图的X坐标     int                 0
     * ViewScrollY        文件上次查看的视图的Y坐标     int                 0
     */

    /*和应用程序相关的Broadcast Action
    ACTION_PACKAGE_ADDED                   一个新应用包已经安装在设备上，数据包括包名（最新安装的包程序不能接收到这个广播）
    ACTION_PACKAGE_REPLACED	            一个新版本的应用安装到设备，替换之前已经存在的版本
    ACTION_PACKAGE_CHANGED           	一个已存在的应用程序包已经改变，包括包名
    ACTION_PACKAGE_REMOVED	            一个已存在的应用程序包已经从设备上移除，包括包名（正在被安装的包程序不能接收到这个广播）
    ACTION_PACKAGE_RESTARTED	            用户重新开始一个包，包的所有进程将被杀死，所有与其联系的运行时间状态应该被移除，包括包名（重新开始包程序不能接收到这个广播）
    ACTION_PACKAGE_DATA_CLEARED	    用户已经清除一个包的数据，包括包名（清除包程序不能接收到这个广播）
    android.intent.action.PACKAGE_INSTALL
     */

    @BindViews({R.id.opendoc_btn_openTxt, R.id.opendoc_btn_openWord, R.id.opendoc_btn_openPpt,
            R.id.opendoc_btn_openExcel, R.id.opendoc_btn_openPdf, R.id.opendoc_btn_chooseFile})
    List<Button> btnList;

    private final String TAG = "OpenDocActivity-->";
    // 下载成功
    public static final int DOWNLOAD_ERROR = 7;
    // 下载失败
    public static final int DOWNLOAD_SUCCESS = 6;

    private WPSContact wps;
    private WPSReceiver receiver;
    private PackageReceiver pReceiver;
    private ProgressDialog mProgressDialog;

    private String openFilePath = "";
    private boolean isInstall = false;

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    // 下载成功,引导安装...
                    File file = (File) msg.obj;
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setDataAndType(Uri.fromFile(file),
                            "application/vnd.android.package-archive");
                    startActivity(intent);
                    break;
                case DOWNLOAD_ERROR:
                    // 下载失败
                    Toast.makeText(OpenDocActivity.this, "", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_opendoc);
        ButterKnife.bind(this);

        receiver = new WPSReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WPSContact.Reciver.ACTION_BACK);
        filter.addAction(WPSContact.Reciver.ACTION_CLOSE);
        filter.addAction(WPSContact.Reciver.ACTION_HOME);
        filter.addAction(WPSContact.Reciver.ACTION_SAVE);
        registerReceiver(receiver, filter);

        pReceiver = new PackageReceiver();
        IntentFilter pFilter = new IntentFilter();
        pFilter.addDataScheme("package");//没有这句就接收不到系统的广播
        pFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        pFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        pFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        pFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        pFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
        pFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
        registerReceiver(pReceiver,pFilter);
    }

    // open file manager
    private void SelectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");// 设置类型，这里是任意类型，任意后缀。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择文件!"), 1);
        } catch (ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 根据返回选择的文件，来进行操作
     **/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (resultCode == Activity.RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            Log.i("uri-->", uri + "");
            String realPath = FileInfoUtils.getPath(this, uri);
            Log.i("realPath-->", realPath + "");

            if (realPath == null) {
                Toast.makeText(this, "获取该文件的路径失败", Toast.LENGTH_LONG).show();
            } else {
//                String fileName = FileInfoUtils.getFileName(realPath);// 文件名
//                String fileSuffix = FileInfoUtils.getFileSuffix(fileName);//文件后缀
                boolean flag = openFile(realPath);
                if (flag == true) {
                    Toast.makeText(OpenDocActivity.this, " 打开文件成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(OpenDocActivity.this, "打开文件失败", Toast.LENGTH_SHORT).show();
                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean openFile(String path) {

        Intent intent = new Intent();
        Bundle bundle = new Bundle();

        bundle.putString(wps.OPEN_MODE, WPSContact.OpenMode.NORMAL);//打开模式
        bundle.putString(wps.THIRD_PACKAGE, WPSContact.PackageName.NORMAL);//第三方包名
        bundle.putBoolean(wps.SEND_SAVE_BROAD, true);
        bundle.putBoolean(wps.SEND_CLOSE_BROAD, true);//发送关闭文件广播
        bundle.putBoolean(wps.CLEAR_BUFFER, true);//清除临时文件
        bundle.putBoolean(wps.CLEAR_TRACE, true);//清除使用记录
        bundle.putBoolean(wps.CLEAR_FILE, false);//关闭文件时删除文件

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setClassName(WPSContact.PackageName.NORMAL, WPSContact.ClassName.NORMAL);
        //其中className为“cn.wps.moffice.documentmanager.PreStartActivity2”，
        // packageName根据版本分别为: ”cn.wps.moffice_eng”(普通版)，”cn.wps.moffice_eng”(英文版)。
        // 要打开的文件通过Uri传入

        File file = new File(path);
        if (file == null || !file.exists()) {
            Log.w(TAG, "file = null or file not exists !");
            return false;
        }

        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        intent.putExtras(bundle);

        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    private void reOpen(String path) {
        openFile(path);
    }

    //判断是否安装了WPS
    public void isInstall() {

        List<PackageInfo> list = getPackageManager().getInstalledPackages(
                PackageManager.GET_PERMISSIONS);

        StringBuilder stringBuilder = new StringBuilder();

        for (PackageInfo packageInfo : list) {
            stringBuilder.append("package name:" + packageInfo.packageName
                    + "\n");
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            stringBuilder.append("应用名称:"
                    + applicationInfo.loadLabel(getPackageManager()) + "\n");
            if (packageInfo.permissions != null) {
                for (PermissionInfo p : packageInfo.permissions) {
                    stringBuilder.append("权限包括:" + p.name + "\n");
                }
            }
            stringBuilder.append("\n");
            if ("cn.wps.moffice_eng".equals(packageInfo.packageName)) {
                isInstall = true;
            }
        }
        System.out.println(isInstall);
    }

    /*
    广播接收者
     */
    private class WPSReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case WPSContact.Reciver.ACTION_BACK:
                    Log.i(TAG, "action back");
                    break;
                case WPSContact.Reciver.ACTION_CLOSE:
                    Log.i(TAG, "action close");
                    break;
                case WPSContact.Reciver.ACTION_HOME:
                    Log.i(TAG, "action home");
                    break;
                case WPSContact.Reciver.ACTION_SAVE:
                    Log.i(TAG, "action save");
                    break;
            }
        }
    }

    private class PackageReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch(action){
                case Intent.ACTION_PACKAGE_ADDED:
                    Log.i(TAG, "added");
                    String packageName = intent.getData().getSchemeSpecificPart();
                    Toast.makeText(context, "安装成功" + packageName, Toast.LENGTH_LONG).show();
                    reOpen(openFilePath);
                    break;
                case Intent.ACTION_PACKAGE_REPLACED:
                    Log.i(TAG, "replaced");
                    break;
                case Intent.ACTION_PACKAGE_CHANGED:
                    Log.i(TAG, "changed");
                    break;
                case Intent.ACTION_PACKAGE_REMOVED:
                    Log.i(TAG, "removed");
                    break;
                case Intent.ACTION_PACKAGE_RESTARTED:
                    Log.i(TAG, "restarted");
                    break;
                case Intent.ACTION_PACKAGE_DATA_CLEARED:
                    Log.i(TAG, "cleared");
                    break;
            }
        }
    }

    /*
    监听
     */
    @OnClick({R.id.opendoc_btn_openTxt, R.id.opendoc_btn_openWord, R.id.opendoc_btn_openPpt,
            R.id.opendoc_btn_openExcel, R.id.opendoc_btn_openPdf, R.id.opendoc_btn_chooseFile})
    public void onClick(View v) {
        String path = "";
        switch (v.getId()) {
            case R.id.opendoc_btn_openTxt:
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/documents/test.txt";
                break;
            case R.id.opendoc_btn_openWord:
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/documents/test.docx";
                break;
            case R.id.opendoc_btn_openPpt:
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/documents/test.pptx";
                break;
            case R.id.opendoc_btn_openExcel:
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/documents/test.xlsx";
                break;
            case R.id.opendoc_btn_openPdf:
                path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/documents/web.pdf";
                break;
            case R.id.opendoc_btn_chooseFile:
                SelectFile();
                break;
        }

        openFilePath = path;

        if (!path.equals("")) {
            isInstall();
            if (isInstall) {
                Log.i(TAG, "is Install");
                openFile(path);
            } else {
                Log.i(TAG, "is not Install");
                System.out.println(Environment.getExternalStorageState());
                Toast.makeText(OpenDocActivity.this, "开始下载...", Toast.LENGTH_SHORT).show();
                mProgressDialog = new ProgressDialog(OpenDocActivity.this);
                mProgressDialog
                        .setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.show();

                final File file1 = new File(
                        Environment.getExternalStorageDirectory(),
                        DownLoadUtil.getFileName("WPS" + ".apk"));
                new Thread() {
                    public void run() {
                        File downloadfile = DownLoadUtil
                                .downLoad(WPS_DownLoad_Url, file1.getAbsolutePath(), mProgressDialog);
                        Message msg = Message.obtain();
                        if (downloadfile != null) {
                            // 下载成功,安装....
                            msg.obj = downloadfile;
                            msg.what = DOWNLOAD_SUCCESS;
                        } else {
                            // 提示用户下载失败.
                            msg.what = DOWNLOAD_ERROR;
                        }
                        handler.sendMessage(msg);
                        mProgressDialog.dismiss();
                    }
                }.start();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

/*
下载工具类
 */
class DownLoadUtil {

    public static final String WPS_DownLoad_Url = "http://mo.wps.cn/dl/?v=cn00563";

    public static File downLoad(String serverpath, String savedfilepath,
                                ProgressDialog pd) {
        try {
            URL url = new URL(serverpath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                int max = conn.getContentLength();
                pd.setMax(max);
                InputStream is = conn.getInputStream();
                File file = new File(savedfilepath);
                if (file.exists()) {
                    return file;
                }
                FileOutputStream fos = new FileOutputStream(file);
                int len = 0;
                byte[] buffer = new byte[1024 * 1024];
                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                }
                fos.flush();
                fos.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String getFileName(String serverurl) {
        return serverurl.substring(serverurl.lastIndexOf("/") + 1);
    }
}

class WPSContact {
    public static final String OPEN_MODE = "OpenMode";// 打开文件的模式。
    public static final String SEND_SAVE_BROAD = "SendSaveBroad";// 文件保存时是否发送广播。
    public static final String SEND_CLOSE_BROAD = "SendCloseBroad";// 文件关闭时是否发送广播
    public static final String THIRD_PACKAGE = "ThirdPackage";// 第三方的包名，关闭的广播会包含该项。
    public static final String CLEAR_BUFFER = "ClearBuffer";// 关闭文件时是否请空临时文件。
    public static final String CLEAR_TRACE = "ClearTrace";// 关闭文件时是否删除使用记录。
    public static final String CLEAR_FILE = "ClearFile";// 关闭文件时是否删除打开的文件。
    public static final String VIEW_PROGRESS = "ViewProgress";// 文件上次查看的进度。
    public static final String AUTO_JUMP = "AutoJump";// 是否自动跳转到上次查看的进度。
    public static final String SAVE_PATH = "SavePath";// 文件保存路径。
    public static final String VIEW_SCALE = "ViewScale";// 文件上次查看的视图的缩放。
    public static final String VIEW_SCALE_X = "ViewScrollX";// 文件上次查看的视图的X坐标。
    public static final String VIEW_SCALE_Y = "ViewScrollY";// 文件上次查看的视图的Y坐标。
    public static final String USER_NAME = "UserName";// 批注的作者。
    public static final String HOMEKEY_DOWN = "HomeKeyDown";// 监听home键并发广播
    public static final String BACKKEY_DOWN = "BackKeyDown";// 监听back键并发广播
    public static final String ENTER_REVISE_MODE = "EnterReviseMode";// 以修订模式打开文档
    public static final String CACHE_FILE_INVISIBLE = "CacheFileInvisible";// Wps生成的缓存文件外部是否可见

    public class OpenMode {
        public static final String NORMAL = "Normal";// 正常模式
        public static final String READ_ONLY = "ReadOnly";// 只读模式
        public static final String READ_MODE = "ReadMode";// 打开直接进入阅读器模式
        // 仅Word、TXT文档支持
        public static final String SAVE_ONLY = "SaveOnly";// 保存模式(打开文件,另存,关闭)
        // 仅Word、TXT文档支持
    }

    public class ClassName {
        public static final String NORMAL = "cn.wps.moffice.documentmanager.PreStartActivity2";// 普通版
        public static final String ENGLISH = "cn.wps.moffice.documentmanager.PreStartActivity2";// 英文版
        public static final String ENTERPRISE = "cn.wps.moffice.documentmanager.PreStartActivity2";// 企业版
    }

    public class PackageName {
        public static final String NORMAL = "cn.wps.moffice_eng";// 普通版
        public static final String ENGLISH = "cn.wps.moffice_eng";// 英文版
    }

    public class Reciver {
        public static final String ACTION_BACK = "com.kingsoft.writer.back.key.down";// 返回键广播
        public static final String ACTION_HOME = "com.kingsoft.writer.home.key.down";// Home键广播
        public static final String ACTION_SAVE = "cn.wps.moffice.file.save";// 保存广播
        public static final String ACTION_CLOSE = "cn.wps.moffice.file.close";// 关闭文件广播
    }
}
